import logging

from django.http import JsonResponse,HttpResponse
from django.views import View
from django_redis import get_redis_connection

from utils.captcha.captcha import captcha
from .constants import IMAGE_CODE_REDIS_EXPIRES
from users.models import Users

logger = logging.getLogger('django')

#1.定义类视图 图片验证码
class ImageCode(View):
    """
    define image code view
    /image_codes/<uuid:image_code_id>
    """

    #2.获取uuid参数 egs:550e8400-e29b-41d4-a716-446655440000
    def get(self,request,image_code_id):
        #3.生成验证码文本及图片
        text, img = captcha.generate_captcha()

        #4.将验证码uuid 及文本存入 redis
        img_id = "img_{}".format(image_code_id)
        con = get_redis_connection(alias="verify")
        con.setex(img_id,IMAGE_CODE_REDIS_EXPIRES,text)

        #5.返回验证码给前端
        logger.info("Image_Code:{}".format(text))
        return HttpResponse(content=img,content_type='image/jpg')

#1.定义类视图 用户名是否已存在
class CheckUserName(View):
    """
    define check user name view
    checkusername/(?P<username>\w[5,20])/
    """

    # 2.获取用户名参数
    def get(self,request,username):
        # 3.查询数据库中是否存在用户名
        count = Users.objects.filter(username=username).count()

        # 4.返回结果
        data = {
            'username':username,
            'count':count
        }
        return JsonResponse(data)


